Skip to content

Conversation

surajmaity1
Copy link
Contributor

@surajmaity1 surajmaity1 commented Feb 24, 2025

Date: Date: 23 Feb, 2025

Developer Name: Suraj Maity ( @surajmaity1 )


Issue Ticket Number

Description

This PR contains feature related to approval and rejection of OOO requests by super-users.

Documentation Updated?

  • Yes
  • No

Under Feature Flag

  • Yes
  • No

Database Changes

  • Yes
  • No

Breaking Changes

  • Yes
  • No

Development Tested?

  • Yes
  • No

Screenshots

Screenshot 1
final.acknowledgement.ooo.mp4
Screenshot 2 1 2

1
2
3

Test Coverage

image
image
image
image

Additional Notes

@surajmaity1 surajmaity1 force-pushed the feat/user-ooo-approve-reject branch from b1c2702 to fb292ef Compare February 24, 2025 16:41
Copy link

coderabbitai bot commented Feb 24, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Summary by CodeRabbit

  • New Features
    • Introduced functionality for acknowledging out-of-office requests, available only to authorized users.
    • Expanded request logging with additional status options that clearly indicate approved or rejected states.
  • Enhancements
    • Improved request validations and update handling for a more consistent experience.
    • Adjusted duplicate request processing to confirm successful creation instead of returning an error.

Walkthrough

This pull request introduces new constants for request logging and authorization related to out-of-office (OOO) requests. It adds a new controller function to handle acknowledgment of OOO requests, modifies existing controllers and validators to support this new flow, and integrates updated service functions to validate and process these requests. Type definitions have been updated accordingly, and integration tests have been adjusted to reflect changes in expected outcomes for duplicate request scenarios.

Changes

File(s) Summary
constants/requests.ts Added constants: REQUEST_ALREADY_APPROVED, REQUEST_ALREADY_REJECTED, and UNAUTHORIZED_TO_ACKNOWLEDGE_OOO_REQUEST.
controllers/oooRequests.ts, controllers/requests.ts Introduced acknowledgeOOORequestController for handling OOO request acknowledgments, updated request property checks (e.g., state to status), and modified function signatures to include next for middleware flow.
middlewares/validators/oooRequests.ts, middlewares/validators/requests.ts Added acknowledgeOOORequestsValidator with Joi schema for validating OOO acknowledgments; updated updateRequestValidator to support the new request type and control flow.
services/oooRequest.ts Added functions validateOOOAcknowledgeRequest and acknowledgeOOORequest to validate and process OOO requests, including Firestore interactions and error handling.
test/integration/requests.test.ts Modified expected outcomes for duplicate request creation: status code changed from 400 to 201, and response message updated from REQUEST_ALREADY_PENDING to REQUEST_CREATED_SUCCESSFULLY.
types/oooRequest.d.ts Updated OooStatusRequest properties (e.g., making until, requestedBy, createdAt, updatedAt, and reason required) and added new types: AcknowledgeOOORequestQuery, AcknowledgeOOORequestBody, AcknowledgeOOORequest.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant Ctrl as Acknowledge Controller
    participant V as Validator
    participant S as OOO Request Service
    participant DB as Firestore

    C->>Ctrl: Send Acknowledge OOO Request (with requestId, body, userId)
    Note over Ctrl: Check query flag & superuser authorization
    Ctrl->>V: (Optional) Validate request (acknowledgeOOORequestsValidator)
    V-->>Ctrl: Validation passed
    Ctrl->>S: Call acknowledgeOOORequest(requestId, body, userId)
    S->>DB: Retrieve OOO request document
    DB-->>S: Return request data
    S->>DB: Validate & update request status
    DB-->>S: Acknowledgment result
    S-->>Ctrl: Return success response
    Ctrl-->>C: Send response with service message
Loading

Possibly related issues

Poem

Hoppin' through the lines of code, I cheer,
New constants and controllers now appear.
OOO requests acknowledged with flair,
Middleware and services join the affair.
With every hop and code delight,
This rabbit celebrates the changes bright!


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@tejaskh3
Copy link
Contributor

could you please add a description to this PR?

@tejaskh3
Copy link
Contributor

and screenshots as well. Even though it is a draft PR, it will help the reviewers.

@surajmaity1 surajmaity1 force-pushed the feat/user-ooo-approve-reject branch 2 times, most recently from 1e0668c to 9d0314b Compare March 11, 2025 13:47
@surajmaity1 surajmaity1 force-pushed the feat/user-ooo-approve-reject branch from 9d0314b to bdbaebe Compare March 18, 2025 02:36
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1d4b457 and ebb4ee4.

📒 Files selected for processing (8)
  • constants/requests.ts (2 hunks)
  • controllers/oooRequests.ts (4 hunks)
  • controllers/requests.ts (3 hunks)
  • middlewares/validators/oooRequests.ts (2 hunks)
  • middlewares/validators/requests.ts (3 hunks)
  • services/oooRequest.ts (1 hunks)
  • test/integration/requests.test.ts (1 hunks)
  • types/oooRequest.d.ts (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
types/oooRequest.d.ts (1)
Learnt from: surajmaity1
PR: Real-Dev-Squad/website-backend#2386
File: test/fixtures/oooRequest/oooRequest.ts:59-60
Timestamp: 2025-03-22T14:28:57.808Z
Learning: The `createOooRequests2` object in test/fixtures/oooRequest/oooRequest.ts still uses the old property names `message` and `state` (instead of `reason` and `status`) because it's specifically used in acknowledging OOO request tests. This naming inconsistency will be fixed by surajmaity1 in a dedicated PR for acknowledging OOO requests.
🧬 Code Definitions (5)
middlewares/validators/requests.ts (2)
types/oooRequest.d.ts (2)
  • AcknowledgeOOORequest (56-61)
  • OooRequestResponse (42-42)
middlewares/validators/oooRequests.ts (1)
  • acknowledgeOOORequestsValidator (42-72)
middlewares/validators/oooRequests.ts (2)
types/oooRequest.d.ts (2)
  • AcknowledgeOOORequest (56-61)
  • OooRequestResponse (42-42)
constants/requests.ts (1)
  • REQUEST_STATE (1-5)
controllers/oooRequests.ts (3)
constants/requests.ts (2)
  • REQUEST_STATE (1-5)
  • UNAUTHORIZED_TO_ACKNOWLEDGE_OOO_REQUEST (46-46)
types/oooRequest.d.ts (2)
  • AcknowledgeOOORequest (56-61)
  • OooRequestResponse (42-42)
services/oooRequest.ts (1)
  • acknowledgeOOORequest (61-135)
controllers/requests.ts (2)
controllers/oooRequests.ts (1)
  • acknowledgeOOORequestController (127-159)
types/oooRequest.d.ts (2)
  • AcknowledgeOOORequest (56-61)
  • OooRequestResponse (42-42)
types/oooRequest.d.ts (2)
constants/requests.ts (1)
  • REQUEST_STATE (1-5)
types/requests.d.ts (2)
  • RequestQuery (11-20)
  • RequestParams (22-24)
🔇 Additional comments (23)
constants/requests.ts (2)

28-29: Well-structured constants for improved request status logging.

These new constants follow the established naming pattern and provide specific log types for already approved or rejected requests, enhancing error handling clarity.


46-46: Clear authorization message for OOO request acknowledgment.

This constant effectively communicates the permission requirements, clearly indicating that only super users can acknowledge OOO requests.

test/integration/requests.test.ts (1)

107-109:

❓ Verification inconclusive

Verify behavioral change in duplicate request handling.

The test now expects a successful response (201) with a "REQUEST_CREATED_SUCCESSFULLY" message when creating a duplicate request, rather than the previous error response (400) with "REQUEST_ALREADY_PENDING". This represents a significant change in how duplicate requests are handled.


🏁 Script executed:

#!/bin/bash
# Verify if this behavior change is intentional by checking the controller logic
# and related PRs or issue discussions

# Check request creation controller logic
rg -A 10 "REQUEST_ALREADY_PENDING" --type ts

Length of output: 6549


Action Required: Confirm Consistency of Duplicate Request Handling Behavior

The integration test in test/integration/requests.test.ts now expects a 201 response with a "REQUEST_CREATED_SUCCESSFULLY" message for duplicate requests. However, our grep results show that other parts of the codebase—such as in test/integration/onboardingExtension.test.ts, controllers/onboardingExtension.ts, and controllers/oooRequests.ts—still rely on the error response with "REQUEST_ALREADY_PENDING" when handling duplicates. Please verify that this behavioral change is intentional and consistent with the overall design. If the change is deliberate, ensure that the updated behavior is clearly documented and that similar endpoints are aligned accordingly.

services/oooRequest.ts (3)

24-59: Well-structured validation function with proper error handling.

The validation function follows good practices by:

  1. Checking request type validity
  2. Verifying request status isn't already approved or rejected
  3. Including appropriate error logging
  4. Using consistent error handling patterns

87-101: Elegant pattern for conditional message and log type selection.

Good use of array destructuring and a ternary operator to concisely determine the appropriate log type and return message based on the request status.


105-122: Comprehensive handling of approved requests.

The function properly creates and adds future status data for approved OOO requests, ensuring the user's status will be updated at the appropriate time.

middlewares/validators/oooRequests.ts (2)

4-4: Updated import to include new type.

The import statement correctly adds the AcknowledgeOOORequest type needed for the new validator function.


42-72: Well-structured validator with appropriate validation rules.

The validator:

  1. Uses Joi schema validation consistently with other validators
  2. Properly validates that status must be APPROVED or REJECTED
  3. Makes comment optional but ensures it's not empty if provided
  4. Includes appropriate error handling with clear error messages
middlewares/validators/requests.ts (3)

4-5: Approve import additions for OOO request acknowledgment.

The import changes correctly include the new AcknowledgeOOORequest type and acknowledgeOOORequestsValidator function needed for the OOO request acknowledgment feature.


133-135: Function parameter type correctly updated to support new OOO acknowledgment flow.

The parameter type expansion to include AcknowledgeOOORequest properly enables the validator to handle both update requests and OOO acknowledgment requests.


140-143: Appropriate conditional handling for undefined type.

This new condition correctly handles the case where the request type is undefined, routing it to the OOO acknowledgment validator. This aligns with the design of having acknowledgment requests without a type field.

controllers/oooRequests.ts (5)

1-1: Approve import updates for OOO acknowledgment feature.

The necessary imports have been added to support the new OOO acknowledgment functionality, including the required types, constants, and service functions.

Also applies to: 13-13, 20-20, 22-22


36-36: Changed property reference from 'state' to 'status'.

The property reference has been updated from state to status, which aligns with the changes in the OooStatusRequest type. This ensures consistency in how the request state is referenced.


127-137: Feature flag implementation for controlled rollout.

The controller properly implements a feature flag check to ensure the feature is only available in development mode. This allows for controlled testing before full release.


138-146: Security check for superuser role.

Good implementation of permission checking to ensure only superusers can acknowledge OOO requests, as required by the feature specification.


155-158: Error handling follows best practices.

The error handling pattern follows best practices by logging the error and passing it to the next middleware for centralized error handling.

controllers/requests.ts (3)

8-9: Approve import updates for OOO acknowledgment functionality.

The necessary imports have been added to support the OOO acknowledgment feature, including the controller function and required types.

Also applies to: 19-19


123-123: Function signature updated to support middleware chain.

Adding the next parameter to the function signature properly enables it to participate in Express middleware chains, which is necessary for error handling in the OOO acknowledgment flow.


126-129: Route undefined type requests to OOO acknowledgment controller.

This new conditional logic appropriately routes requests with undefined type to the OOO acknowledgment controller, aligning with the design where acknowledgment requests don't specify a type.

types/oooRequest.d.ts (4)

12-20: Type definitions updated to support OOO request flow.

The updates to the OooStatusRequest type properly reflect the new requirements for OOO requests, including required fields and proper type constraints. The change from state to status aligns with the naming convention being used elsewhere in the codebase.


47-49: Feature flag query parameter type definition.

The AcknowledgeOOORequestQuery type correctly extends RequestQuery with the optional dev parameter used for feature flagging.


51-54: OOO acknowledgment request body type properly defined.

The body type for acknowledging OOO requests is well-structured with the required status field and optional comment field, matching the validation schema in the middleware.


56-61: Complete type definition for the OOO acknowledgment request.

The AcknowledgeOOORequest type properly extends the base Request type with all necessary properties for handling OOO acknowledgments, ensuring type safety throughout the request processing flow.

@surajmaity1 surajmaity1 force-pushed the feat/user-ooo-approve-reject branch from 8522627 to 5540a2e Compare April 3, 2025 01:36
@surajmaity1 surajmaity1 force-pushed the feat/user-ooo-approve-reject branch from 08ff3d1 to 04d1bfe Compare April 15, 2025 02:04
@surajmaity1 surajmaity1 force-pushed the feat/user-ooo-approve-reject branch from 04d1bfe to 6b497b1 Compare April 15, 2025 02:45
Copy link
Member

@AnujChhikara AnujChhikara left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @surajmaity1,
One of the tests is failing. Could you please take a look when you get a chance?
Thanks!

@surajmaity1
Copy link
Contributor Author

surajmaity1 commented Apr 15, 2025

Hi @surajmaity1,
One of the tests is failing. Could you please take a look when you get a chance?
Thanks!

Hi @AnujChhikara ,

The test case for the creation of the OOO request has failed. However, I have already addressed this test case in the PR -
#2386

Thank you.

@surajmaity1
Copy link
Contributor Author

Proof missing for case when after approving request, user status becomes OOO.

After the OOO request is approved, the user's futureStatus is updated accordingly. A scheduled cron job then processes this status change and updates the user's status to "OOO" at the appropriate time.

@surajmaity1 surajmaity1 changed the title feat: acknowledge OOO request Add feature to approve or reject OOO request May 5, 2025
pankajjs
pankajjs previously approved these changes May 5, 2025
Copy link
Contributor

@pankajjs pankajjs left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM
My comments have been resolved. Therefore approved it.

@Achintya-Chatterjee Achintya-Chatterjee self-requested a review May 5, 2025 19:11
@surajmaity1 surajmaity1 dismissed stale reviews from Achintya-Chatterjee and pankajjs via 5296265 May 6, 2025 06:52
@surajmaity1 surajmaity1 force-pushed the feat/user-ooo-approve-reject branch 2 times, most recently from 8fa2496 to 7f2e9dc Compare May 6, 2025 17:43
vinit717
vinit717 previously approved these changes May 6, 2025
vikasosmium
vikasosmium previously approved these changes May 6, 2025
@surajmaity1 surajmaity1 force-pushed the feat/user-ooo-approve-reject branch from 7f2e9dc to 5aa7e39 Compare May 6, 2025 19:22
vinit717
vinit717 previously approved these changes May 6, 2025

if(!dev) return res.boom.notImplemented("Feature not implemented");

const isSuperuser = req.userData.roles?.super_user;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add optional chaining to req.userData?.roles to prevent potential null/undefined errors if userData isn't properly initialized.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi Amit sir,
it's fixed.


const requestBody = req.body;
const superUserId = req.userData.id;
const requestId = req.params.id;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please add validation for requestId

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi Amit sir,
it's fixed.

* @param {OooRequestResponse} res - The response object.
* @returns {Promise<OooRequestResponse>} Resolves with success or failure.
*/
export const acknowledgeOooRequest = async (
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT: please move the entire function body inside the try-catch block to capture all potential errors, including those that might occur during parameter extraction

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi Amit sir,
it's fixed.

@iamitprakash
Copy link
Member

@surajmaity1 please use below

export const acknowledgeOooRequest = async (
  req: AcknowledgeOooRequest,
  res: OooRequestResponse,
  next: NextFunction
): Promise<OooRequestResponse> => {
  try {
    const dev = req.query.dev === "true";
    if (!dev) return res.boom.notImplemented("Feature not implemented");
    
    const isSuperuser = req.userData?.roles?.super_user;
    if (!isSuperuser) {
      return res.boom.forbidden(UNAUTHORIZED_TO_UPDATE_REQUEST);
    }
    
    const requestBody = req.body;
    const superUserId = req.userData.id;
    const requestId = req.params.id;
    
    if (!requestId) {
      return res.boom.badRequest("Request ID is required");
    }
    
    const response = await oooRequestService.acknowledgeOooRequest(requestId, requestBody, superUserId);
    return res.status(200).json({
      message: response.message,
    });
  }
  catch (error) {
    logger.error(ERROR_WHILE_ACKNOWLEDGING_REQUEST, error);
    next(error);
    return res;
  }
};

@vikasosmium vikasosmium self-requested a review May 6, 2025 21:01
@surajmaity1 surajmaity1 dismissed stale reviews from vinit717 and Achintya-Chatterjee via 680fe42 May 7, 2025 03:48
@surajmaity1 surajmaity1 force-pushed the feat/user-ooo-approve-reject branch from 5aa7e39 to 680fe42 Compare May 7, 2025 03:48
@surajmaity1
Copy link
Contributor Author

@surajmaity1 please use below

export const acknowledgeOooRequest = async (
  req: AcknowledgeOooRequest,
  res: OooRequestResponse,
  next: NextFunction
): Promise<OooRequestResponse> => {
  try {
    const dev = req.query.dev === "true";
    if (!dev) return res.boom.notImplemented("Feature not implemented");
    
    const isSuperuser = req.userData?.roles?.super_user;
    if (!isSuperuser) {
      return res.boom.forbidden(UNAUTHORIZED_TO_UPDATE_REQUEST);
    }
    
    const requestBody = req.body;
    const superUserId = req.userData.id;
    const requestId = req.params.id;
    
    if (!requestId) {
      return res.boom.badRequest("Request ID is required");
    }
    
    const response = await oooRequestService.acknowledgeOooRequest(requestId, requestBody, superUserId);
    return res.status(200).json({
      message: response.message,
    });
  }
  catch (error) {
    logger.error(ERROR_WHILE_ACKNOWLEDGING_REQUEST, error);
    next(error);
    return res;
  }
};

Hi Amit sir,
it's added.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.